package com._520it.crm.service.impl;

import com._520it.crm.domain.Employee;
import com._520it.crm.domain.Role;
import com._520it.crm.mapper.EmployeeMapper;
import com._520it.crm.page.PageResult;
import com._520it.crm.query.EmployeeQueryObject;
import com._520it.crm.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * Created by ASUS on 2017/10/9.
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService{
    @Autowired
    private EmployeeMapper employeeMapper;

    private Employee employee = new Employee();



    @Override
    public int deleteByPrimaryKey(Long id) {
        employee.setAdmin(1);
        return employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Employee record) {
        record.setAdmin(0);
        int count = employeeMapper.insert(record);
        //插入中间表的数据
       for (Role role : record.getRoles()){
           employeeMapper.insertRoleRelation(record.getId(),role.getId());
       }
        return  count;
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Employee record) {
        employeeMapper.deleteRoleRelation(record.getId());
        for (Role role : record.getRoles()){
            employeeMapper.insertRoleRelation(record.getId(),role.getId());
        }
        return employeeMapper.updateByPrimaryKey(record);
    }


    public PageResult query(EmployeeQueryObject qo) {
        Integer totalCount = employeeMapper.queryforCount(qo);
        if (totalCount==0){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Employee> data = employeeMapper.queryforList(qo);
        return new PageResult(totalCount,data);
    }
    @Override
    public Employee queryByName(String username) {
        return employeeMapper.queryByName(username);
    }
}
